<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="订单号" prop="code">
        <el-input v-model="queryParams.code" placeholder="请输入订单号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="客户单号" prop="relateBill2">
        <el-input v-model="queryParams.relateBill2" placeholder="请输入客户单号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="分段订单状态" prop="status">
        <MultipleSelect :selectOptions="dict.type.OrderStatus" :mulSelectLoading="false" :mulSelecteds="queryParams.statusArray"
                        @update:updateMultipleSelect="val => queryParams.statusArray = val">
        </MultipleSelect>
      </el-form-item>
      <el-form-item label="目的网点" prop="jcToOrganizationId">
        <el-select clearable filterable v-model="queryParams.jcToOrganizationId" placeholder="请选择目的网点">
          <el-option v-for="dict in dict.type.DB_JC_ORG" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="收货客户" prop="receivingPerson">
        <el-input v-model="queryParams.receivingPerson" placeholder="请输入收货客户" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="订单日期">
        <el-date-picker v-model="queryParams.daterangeTime" style="width: 240px" value-format="yyyy-MM-dd"
                        type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="success" icon="el-icon-more" size="mini" @click="moreFilterQuery">更多查询</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-plus" size="mini" :disabled="single" @click="handleEditSize" v-hasPermi="['order:led:sign']">修改件、重、尺</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-plus" size="mini" :disabled="single" @click="handleCarryLed" v-hasPermi="['order:led:sign']">配载到运单</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-download" size="mini" @click="handleExport">导出分段订单</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ledList" @selection-change="handleSelectionChange">
      <el-table-column width="55" type="selection" align="center" />
      <el-table-column align="left" fixed label="订单" width='170'>
        <template #default="scope">
          <div>{{ scope.row.code }}</div>
          <div>{{ scope.row.fromOrganizationName }} -> {{ scope.row.toOrganizationName }}</div>
          <div>订单日期:{{ parseTime(scope.row.time, '{y}-{m}-{d}') }}</div>
          <dict-tag :options="dict.type.OrderStatus" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column align="left" label="单号" prop="relateBill1" width='200'>
        <template #default="scope">
          <div>发货单号:{{ scope.row.relateBill1 }}</div>
          <div>客户单号:{{ scope.row.relateBill2 }}</div>
        </template>
      </el-table-column>
      <el-table-column align="left" label="运单" prop="shipmentCode" width='200'>
        <template #default="scope">
          <div v-if="scope.row.shipmentCode">运单:{{ scope.row.shipmentCode }}</div>
          <div v-if="scope.row.driverName">司机：{{ scope.row.driverName }}</div>
          <div v-if="scope.row.driverIphone">电话：{{ scope.row.driverIphone }}</div>
        </template>
      </el-table-column>
      <el-table-column width='200' label="客户" align="left" prop="customerName" show-overflow-tooltip>
        <template #default="scope">
          <div>名称:{{ scope.row.customerName }}</div>
          <div>类型:<dict-tag :options="dict.type.CustomerType" :value="scope.row.customerType" style="display: inline-block"/></div>
          <div>合同超期:<dict-tag :options="dict.type.CommIsNot" :value="scope.row.customerIsExceed" style="display: inline-block" /></div>
        </template>
      </el-table-column>
      <el-table-column align="left" label="订单时间" prop="factLeaveTime" width='180'>
        <template #default="scope">
          <div v-if="scope.row.factLeaveTime">实际发运时间:{{parseTime(scope.row.factLeaveTime, '{y}-{m}-{d} {h}:{i}')}}</div>
          <div v-if="scope.row.factArriveTime">实际到达时间:{{ parseTime(scope.row.factArriveTime, '{y}-{m}-{d} {h}:{i}') }}</div>
          <div v-if="scope.row.planLeaveTime">要求发运时间: {{parseTime(scope.row.planLeaveTime, '{y}-{m}-{d} {h}:{i}')}}</div>
          <div v-if="scope.row.planArriveTime">要求到达时间: {{ parseTime(scope.row.planArriveTime, '{y}-{m}-{d} {h}:{i}') }}</div>
        </template>
      </el-table-column>
      <el-table-column width="290" label="收货" align="left" prop="receivingPerson" show-overflow-tooltip>
        <template #default="scope">
          <div>收货人:{{ scope.row.receivingPerson }}</div>
          <div>电话{{ scope.row.receivingPhone }}</div>
          <div>地址{{ scope.row.receivingAddress }}</div>
        </template>
      </el-table-column>
      <el-table-column align="left" label="交付" prop="handoverType" width='150'>
        <template #default="scope">
          <div>
            交付方式
            <dict-tag :options="dict.type.HandoverType" :value="scope.row.handoverType" style="display: inline-block"/>
          </div>
          <div>
            是否回单:
            <dict-tag :options="dict.type.CommIsNot" :value="scope.row.isBack" style="display: inline-block"/>
          </div>
          <div v-if="scope.row.isBack === 1">回单份数: {{ scope.row.backNumber }}</div>
          <div>
            运输性质
            <dict-tag :options="dict.type.TransportPro" :value="scope.row.transportPro" style="display: inline-block"/>
          </div>
        </template>
      </el-table-column>
      <el-table-column width='120' label="件数(件)" align="left" prop="number">
        <template #default="scope">
          <div>件数:{{ scope.row.number }}</div>
          <div>重量(kg):{{ scope.row.weight }}</div>
          <div>体积(平方):{{ scope.row.volume }}</div>
        </template>
      </el-table-column>
      <el-table-column width='120' label="创建时间" align="center" prop="createTime" />
      <el-table-column label="创建人" align="center" prop="createName" />
      <el-table-column align="left" label="签收" prop="qsTime" width='200' fixed="right">
        <template #default="scope">
          <div>签收时间:{{ scope.row.qsTime ? parseTime(scope.row.qsTime, '{y}-{m}-{d} {h}:{i}') : '--' }}</div>
          <div>签收人:{{ scope.row.qsPerson || '--' }}</div>
          <div class="mt10">
            <el-button size="mini" type="primary" @click="openTrack(scope.row)">在途跟踪</el-button>
          </div>
          <div class="mt10">
            <el-button v-if="scope.row.qsImgs" size="mini" type="primary" @click="openPic(scope.row)">查看签收单
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <el-dialog :close-on-click-modal="false" title="订单追踪" :visible.sync="orderTrackVisible" width="700px" append-to-body>
      <div class="block" style="max-height: 600px; overflow-y: scroll;">
        <el-timeline>
          <el-timeline-item v-for="(item, index) in orderTrackList" :key="index" :timestamp="item.time" placement="top">
            <el-card>
              <h4>{{ item.event }}</h4>
              <p>{{ item.createName }} 提交于 {{ item.time }}</p>
              <div v-if="item.imgUrls">
                <el-image v-for="(img, ind) in item.imgUrls" :key="ind" style="width: 100px; height: 100px;margin: 10px 10px;" :src="img" :preview-src-list="item.imgUrls">
                </el-image>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-dialog>

    <el-dialog title="查看图片" :visible.sync="openPicVisible" width="800px" append-to-body>
      <el-image v-for="(pic, index) in openPicList" :key="index" :src="pic" style="height: 100px;margin: 20px 20px;" :preview-src-list="openPicList" />
    </el-dialog>

    <more-query ref="moreQuery" :query-params="queryParams" @ok="handleQuery"></more-query>

    <el-dialog :close-on-click-modal="false" title="修改件重尺" :visible.sync="openEditNum" width="700px" append-to-body>
      <el-form :model="numAndSizeForm" ref="numAndSizeForm" size="small" :inline="true" label-width="80px">
        <el-form-item label="原数量">
          <el-input type="number" v-model="numAndSizeForm.oldNumber" placeholder="请输入原数量" readonly="readonly" />
        </el-form-item>
        <el-form-item label="新数量">
          <el-input type="number" v-model="numAndSizeForm.newNumber" placeholder="请输入新数量" clearable />
        </el-form-item>
        <el-form-item label="原体积">
          <el-input type="number" v-model="numAndSizeForm.oldVolume" placeholder="请输入原体积" readonly="readonly" />
        </el-form-item>
        <el-form-item label="新体积">
          <el-input type="number" v-model="numAndSizeForm.newVolume" placeholder="请输入新体积" clearable />
        </el-form-item>
        <el-form-item label="原重量">
          <el-input type="number" v-model="numAndSizeForm.oldWeight" placeholder="请输入原重量" readonly="readonly" />
        </el-form-item>
        <el-form-item label="新重量">
          <el-input type="number" v-model="numAndSizeForm.newWeight" placeholder="请输入新重量" clearable />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelNumAndSizeForm">取 消</el-button>
        <el-button type="primary" @click="submitSizeForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listLed, getLed, saveLedSize } from "@/api/order/led";
import { listOrderTrackByOrderId } from "@/api/order/orderTrack";
import MoreQuery from "@/views/order/led/component/moreQuery.vue";
import MultipleSelect from "@/components/MultipleSelect/index.vue";

export default {
  name: "Led",
  components: {MultipleSelect, MoreQuery },
  dicts: ['OrderStatus', 'CommIsNot', 'TransportPro', 'HandoverType', 'DB_JC_ORG', 'CustomerType'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // ledId
      ledId: null,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 分段订单表格数据
      ledList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        name: null,
        status: null,
        statuses: null,
        statusArray: [],
        backNumber: null,
        customerIsExceed: null,
        customerName: null,
        customerType: null,
        factArriveTime: null,
        factLeaveTime: null,
        feeType: null,
        handoverType: null,
        isAbnormal: null,
        isBack: null,
        number: null,
        actNumber: null,
        orderMileage: null,
        planArriveTime: null,
        planLeaveTime: null,
        relateBill1: null,
        relateBill2: null,
        relateBill3: null,
        relateBill4: null,
        relateBill5: null,
        salePerson: null,
        shipmentMethod: null,
        time: null,
        transportPro: null,
        value: null,
        volume: null,
        weight: null,
        jcCustomerId: null,
        jcEndZoneId: null,
        jcOrderId: null,
        jcOrganizationId: null,
        jcPrescoId: null,
        jcDispatchId: null,
        jcStartZoneId: null,
        jcToOrganizationId: null,
        routerOrgIds: null,
        jcZoneStoreroomId: null,
        jcFormOrganizationId: null,
        type: null,
        agent: null,
        qsTime: null,
        qsPerson: null,
        qsImgs: null,
        jzWeight: null,
        arrivePay: null,
        jcShipmentId: null,
        // 计划发运时间
        daterangePlanLeaveTime: [],
        // 运单ID时间范围
        daterangeCreateTime: [],
        // 运单ID时间范围
        daterangeModifyTime: [],
        // 运单ID时间范围
        daterangeFactArriveTime: [],
        // 运单ID时间范围
        daterangeFactLeaveTime: [],
        // 运单ID时间范围
        daterangeTime: [],
        // 运单ID时间范围
        daterangeQsTime: [],
      },
      // 表单校验
      rules: {
        qsImgs: [
          { required: true, message: "签收图片", trigger: "blur" }
        ],
      },
      orderTrackList: [],
      orderTrackVisible: false,
      openPicVisible: false,
      openPicList: [],
      openEditNum: false,
      numAndSizeForm: {
        oldNumber: null,
        oldVolume: null,
        oldWeight: null,
        newNumber: null,
        newVolume: null,
        newWeight: null,
      },
      numAndSizeRules: {
        oldNumber: [
          { required: true, message: "原数量", trigger: "blur" }
        ],
        oldVolume: [
          { required: true, message: "原体积", trigger: "blur" }
        ],
        oldWeight: [
          { required: true, message: "原重量", trigger: "blur" }
        ],
        newNumber: [
          { required: true, message: "新数量", trigger: "blur" }
        ],
        newVolume: [
          { required: true, message: "新体积", trigger: "blur" }
        ],
        newWeight: [
          { required: true, message: "新重量", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询分段订单列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.queryParams.daterangePlanLeaveTime && '' !== this.queryParams.daterangePlanLeaveTime) {
        this.queryParams.params["beginPlanLeaveTime"] = this.queryParams.daterangePlanLeaveTime[0];
        this.queryParams.params["endPlanLeaveTime"] = this.queryParams.daterangePlanLeaveTime[1];
      }
      if (null != this.queryParams.daterangeCreateTime && '' !== this.queryParams.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.queryParams.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.queryParams.daterangeCreateTime[1];
      }
      if (null != this.queryParams.daterangeModifyTime && '' !== this.queryParams.daterangeModifyTime) {
        this.queryParams.params["beginModifyTime"] = this.queryParams.daterangeModifyTime[0];
        this.queryParams.params["endModifyTime"] = this.queryParams.daterangeModifyTime[1];
      }
      if (null != this.queryParams.daterangeFactArriveTime && '' !== this.queryParams.daterangeFactArriveTime) {
        this.queryParams.params["beginFactArriveTime"] = this.queryParams.daterangeFactArriveTime[0];
        this.queryParams.params["endFactArriveTime"] = this.queryParams.daterangeFactArriveTime[1];
      }
      if (null != this.queryParams.daterangeFactLeaveTime && '' !== this.queryParams.daterangeFactLeaveTime) {
        this.queryParams.params["beginFactLeaveTime"] = this.queryParams.daterangeFactLeaveTime[0];
        this.queryParams.params["endFactLeaveTime"] = this.queryParams.daterangeFactLeaveTime[1];
      }
      if (null != this.queryParams.daterangeTime && '' !== this.queryParams.daterangeTime) {
        this.queryParams.params["beginTime"] = this.queryParams.daterangeTime[0];
        this.queryParams.params["endTime"] = this.queryParams.daterangeTime[1];
      }
      if (null != this.queryParams.daterangeQsTime && '' !== this.queryParams.daterangeQsTime) {
        this.queryParams.params["beginQsTime"] = this.queryParams.daterangeQsTime[0];
        this.queryParams.params["endQsTime"] = this.queryParams.daterangeQsTime[1];
      }
      if (this.queryParams.statusArray) {
        this.queryParams.statuses = this.queryParams.statusArray.join(",");
      }
      listLed(this.queryParams).then(response => {
        this.ledList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancelNumAndSizeForm() {
      this.openEditNum = false;
      this.resetNumAndSizeForm();
    },
    // 表单重置
    resetNumAndSizeForm() {
      this.numAndSizeForm = {
        qsImgs: null
      };
      this.resetForm("numAndSizeForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.daterangePlanLeaveTime = [];
      this.queryParams.daterangeCreateTime = [];
      this.queryParams.daterangeModifyTime = [];
      this.queryParams.daterangeFactArriveTime = [];
      this.queryParams.daterangeFactLeaveTime = [];
      this.queryParams.daterangeTime = [];
      this.queryParams.daterangeQsTime = [];
      this.resetForm("queryForm");
      this.$refs.moreQuery.resetQuery();
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleExport() {
      this.download('/order/led/export', {
        ...this.queryParams
      }, `导出分段订单_${new Date().getTime()}.xlsx`)
    },
    // 配载到运单
    handleCarryLed() {
      alert("开发中")
    },
    handleEditSize() {
      this.ledId = this.ids
      // 获取数据
      getLed(this.ledId).then(response => {
        if(response.data){
          this.numAndSizeForm.oldNumber = response.data.number
          this.numAndSizeForm.oldVolume = response.data.volume
          this.numAndSizeForm.oldWeight = response.data.weight
          this.numAndSizeForm.ledId = response.data.id
          this.openEditNum = true
       }
      });
    },
    /** 提交按钮 */
    submitSizeForm() {
      this.$refs["numAndSizeForm"].validate(valid => {
        if (valid) {
          saveLedSize(this.numAndSizeForm).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.openEditNum = false
            this.getList();
          });
        }
      });
    },
    openTrack(row) {
      this.orderTrackVisible = true
      this.orderTrackList = []
      /** 查询订单追踪列表 */
      this.loading = true;
      listOrderTrackByOrderId(row.orderId).then(response => {
        this.loading = false;
        this.orderTrackList = response.data;
        // 处理图片地址
        if (this.orderTrackList.length > 0) {
          this.orderTrackList.forEach(item => {
            if (item.imgs) {
              // 每个图片地址都加上baseUrl
              item.imgUrls = item.imgs.split(',').map(d => process.env.VUE_APP_BASE_API + d)
            }
          })
          debugger
        }
      });
    },
    openPic(row) {
      this.openPicVisible = true
      this.openPicList = []
      if (row.qsImgs) {
        this.openPicList = row.qsImgs.split(',').map(d => process.env.VUE_APP_BASE_API + d)
      }
    },
    moreFilterQuery() {
      this.$refs.moreQuery.moreFilterQuery();
    },
  }
};
</script>
